Ti.include('../class/db.js');
Ti.include('../class/network.js');
Ti.include('../viewHelper/ideaDetailsViews.js');
Ti.include('../viewHelper/commentViews.js');

var win = Ti.UI.currentWindow;

var objIdea = Db.retrieveIdea(win.idIdea);
var objSolucions = null;
var views = ideaDetailsViews.getViews(objIdea);
var toolbarItems =[];

function findLinks (tx){
	var response = [];
	var exp =/(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*)/mig;
	var hits = tx.match(exp);
	if (hits) {
		for (var i in hits){
			if (!isNaN(i)){
				response.push(hits[i]);
			}
		}
		Ti.API.info("links trobats:"+response);
	}else{
		Ti.API.info("link no trobat text");
	}
	return response;
}
var links = findLinks(objIdea.ds);

if (links.length >0){
	links.push('Cancel');
	var save = Ti.UI.createButton({
		systemButton:Titanium.UI.iPhone.SystemButton.ACTION
	});
	save.addEventListener('click', function()
	{
		var dialog = Ti.UI.createOptionDialog({
			options:links,
			cancel:links.length -1,
			title:L('Enllaços en el text')
		});
		dialog.addEventListener('click',function(e){ Ti.Platform.openURL(links[e.index]);});
		dialog.show();
	});
	toolbarItems.push(save);
}

if(Ti.App.user.hasToken()){
	var addOptions = [L('Comentari'),L('Cancelar')];

	var comment = Ti.UI.createButton({
		systemButton:Titanium.UI.iPhone.SystemButton.ADD
	});
	comment.addEventListener('click', function()
	{
		var commentdialog = Ti.UI.createOptionDialog({
			options:addOptions,
			cancel:1,
			title:L('Afegir...')
		});
		commentdialog.addEventListener('click',function(e){ 
			if (e.index == 0){
				commentViews.show(win.idIdea);
			}
		});
		commentdialog.show();
	});

	toolbarItems.push(comment);
}

if (toolbarItems.length >0){
	win.barColor = '#333';
	win.toolbar=toolbarItems;
}

win.add(views.activityIndicator);
win.addEventListener('focus', function (e){
	Ti.API.info("ideaDetailsWindow focus");
	Db.markIdeaAsRead(win.idIdea);
	Ti.App.fireEvent('fillTorrentTablesFromDatabase');
	Ti.App.tabGroup.animate({bottom:-50,duration:500});
});

win.addEventListener('close', function (e){
	Ti.API.info("ideaDetailsWindow close");
	Ti.App.tabGroup.animate({bottom:0,duration:500});
	
});

function getFormatedDate(newDate,pubDate){
	newDate.setTime( pubDate * 1000 );
	var sDay = newDate.getDate() +"";
	if (sDay.length==1){
		sDay= '0'+sDay;
	}
	var sMonth = (newDate.getMonth() + 1) +"";
	if (sMonth.length==1){
		sMonth= '0'+sMonth;
	}
	var sYear = newDate.getUTCFullYear();
	var sHours = newDate.getHours() + "";
	if (sHours.length==1){
		sHours= '0'+sHours;
	}
	var sMinutes = newDate.getMinutes() + "";
	if (sMinutes.length==1){
		sMinutes= '0'+sMinutes;
	}
	var sSeconds = newDate.getSeconds() + "";
	if (sSeconds.length==1){
		sSeconds= '0'+sSeconds;
	}
	
	var sDate = sDay+ '/'+ sMonth+ '/' + sYear + ' ' + sHours + ":" + sMinutes + ":" + sSeconds;
	return sDate;
	
}

Ti.App.addEventListener('comentarisDownloadOk', function(response){
	views.activityIndicator.hide();
	//Ti.API.info("comentarisDownloadOk response:"+response.text);
	var responseJson = JSON.parse(response.text);
	var rowsComentaris = [];
	var currentComentari = null;
	var tmpRow = null;
	var newDate = new Date();
	var dateString = null;
	
	for(var i in responseJson){
		if (!isNaN(i)){
			currentComentari = responseJson[i];
			dateString =  getFormatedDate(newDate,currentComentari.pubDate);
			currentComentari.headerText = currentComentari.author + " " + L("at") + " " + dateString;
			rowsComentaris = ideaDetailsViews.getComentariRowFromData(rowsComentaris,currentComentari);
		}
	}
	if (rowsComentaris.length == 0){
		tmpRow = ideaDetailsViews.getNoComentariRow();
		rowsComentaris.push(tmpRow);
	}
	views.comentarisTableView.setData(rowsComentaris);
});

Ti.App.addEventListener('getVotesFromIdeaOk',function(votsObj){
	if(votsObj.vots.length >0){
		var tmpVot = null;
		for (var i in votsObj.vots){
			if (!isNaN(i)){
				tmpVot = votsObj.vots[i];
				Db.sincronitzarVotSolucio(tmpVot.solucio,tmpVot.vot);
			}
		}
	}
});
Ti.App.network_user.getVotesFromIdea(win.idIdea);

Ti.App.addEventListener('updateSolucionsTableView', function(){
	objSolucions = Db.retrieveSolucionsByIdeaId(win.idIdea);
	views.solucionsTableView.setData(ideaDetailsViews.getSolucionsRowsFromData(objSolucions));
});

Ti.App.addEventListener('comentarisDownloadKo', function(statusObj){
	views.activityIndicator.hide();
	if(statusObj.status != 'no network'){
		var alertDialog = Titanium.UI.createAlertDialog({
			title: L('WARNING'),
			message: L('Your device is not online.'),
			buttonNames: ['OK']
        });
		alertDialog.show();
		//alert("ERROR1 "+ statusObj.status);
	}
});

Ti.App.addEventListener('startDownloadingComments', function (){
	views.activityIndicator.show();
	//Ti.API.info("views.activityIndicator.message:"+views.activityIndicator.message);
	network.getComentaris(win.idIdea);
});
if (parseFloat(Titanium.Platform.version) > 4.1){ // en esta ventana, la tabbar no funciona en ios < 4.2	
	win.titleControl.addEventListener('click', function(e){
		Ti.API.info("barraBotons.click: e.index:"+e.index);
		switch (e.index){
			case 0: // ideas
				views.ideasTableView.show();
				views.solucionsTableView.hide();
				views.comentarisTableView.hide();
				break;
			
			case 1: // solucions
				views.ideasTableView.hide();
				views.solucionsTableView.show();
				views.comentarisTableView.hide();
				break;
			
			case 2: // comentaris
				views.ideasTableView.hide();
				views.solucionsTableView.hide();
				views.comentarisTableView.show();
				Ti.App.fireEvent('startDownloadingComments');
				break;
		}
	});
}
views.solucionsTableView.addEventListener('click',  function(elem){
	var idSolucio = elem.rowData.idSolucio;
	var numSolucio = elem.rowData.numSolucio;
	if (idSolucio != null){
		var solucioWindow = ideaDetailsViews.getSolucioWindowByData(idSolucio,numSolucio); 
		Ti.App.ideaNavigationGroup.open(solucioWindow,{animated:true});
	}
});

views.titolIdeaView.add(views.titolIdeaLabel);
win.add(views.titolIdeaView);

views.ideasTableView.top = views.titolIdeaView.height;
views.solucionsTableView.top = views.titolIdeaView.height;
views.comentarisTableView.top = views.titolIdeaView.height;

views.ideaDetailsRow.add(views.ideaDescriptionLabel);
views.ideasTableView.setData([views.ideaDetailsRow]);


win.add(views.ideasTableView);
win.add(views.solucionsTableView);
win.add(views.comentarisTableView);

Ti.App.fireEvent('updateSolucionsTableView');